<?php

class Synchronizer {

	private $siblings = array();
	private $files = array();

	function Synchronizer($siblings) {
		$this->siblings = $siblings;
		
		$this->get_files();
	}

	function get_files() {
		$current_files = Files::get_list();

		foreach($this->siblings as $sibling) {
			$this->get_file_list($sibling);
		}

		foreach($this->files as $server => $files) {
			foreach($files as $file) {
				/** Make sure we have an absolute URL */
				$file['url'] = SimplePie_Misc::absolutize_url($file['file'], $server);
				$id = md5($file['file']);
				if( !isset($current_files[$id]) || $current_files[$id] < $file['last_modified']) {
					$this->sync_file($file);
					$current_files[$id] = array(
						'file' => $file['file'],
						'last_modified' => $file['last_modified']
					);
				}
			}
		}
	}

	function get_file_list($sibling) {
		$url = $sibling['url'] . 'remote.php';
		if($sibling['type'] != 'public')
			$url .= '?' . $sibling['secret'];
		$list = new SimplePie_File($url);
		
		if(!$list->success || $list->status_code == 404)
			return false;

		$this->files[$sibling['url']] = unserialize($list->body);
	}

	function sync_file($file) {
		// Get the URL to the remote file
		$remote = $file['url'];

		$download_file = new RemoteFile($remote);
		$temp_file = $download_file->filename;
		unset($download_file);
		/* unlink($temp_file); */

		if ( ErrorHandler::is_error($temp_file) )
			return ErrorHandler::instance()->add('download_failed', __('Download failed.'), $temp_file->get_error_message());

		$file_dir = MP_PATH . '/files/';

		$dirs = explode('/', dirname($file['file']));
		// Remove the first ('files') entry
		array_shift($dirs);

		$filepath = $file_dir;
		// Loop through each of the items and check that the folder exists.
		foreach($dirs as $dir) {
			var_dump($dirs);
			$tmppath .= $dir . '/';
			if ( !@is_dir($file_dir . $tmppath) )
				if ( !@mkdir($file_dir . $tmppath, 0755) )
					return ErrorHandler::instance()->add('mkdir_failed', __('Could not create directory'), $file_dir . $tmppath);
		}
		$filepath .= basename($file['file']);
		var_dump($filepath);
		//die();

		if( copy($temp_file, $filepath) && file_exists($filepath) ) {
			echo "saved to $filepath";
		}
		unlink($temp_file);
	}
}